package work.konbai.bmc.cms.service.impl;

import work.konbai.bmc.cms.dao.KindDao;
import work.konbai.bmc.cms.domain.KindDO;
import work.konbai.bmc.cms.service.KindService;
import work.konbai.bmc.common.domain.Tree;
import work.konbai.bmc.common.utils.BuildTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author KonBAI
 * @version 1.0
 * Create by 2020/02/07 22:12
 */
@Service
public class KindServiceImpl implements KindService {
    @Autowired
    private KindDao kindMapper;

    @Override
    public KindDO get(Long kindId) {
        return kindMapper.get(kindId);
    }

    @Override
    public List<KindDO> list(Map<String, Object> map) {
        return kindMapper.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return kindMapper.count(map);
    }

    @Override
    public int save(KindDO kind) {
        return kindMapper.save(kind);
    }

    @Override
    public int update(KindDO kind) {
        return kindMapper.update(kind);
    }

    @Override
    public int remove(Long kindId) {
        return kindMapper.remove(kindId);
    }

    @Override
    public int batchRemove(Long[] kindIds) {
        return kindMapper.batchRemove(kindIds);
    }

    @Override
    public Tree<KindDO> getTree() {
        List<Tree<KindDO>> trees = new ArrayList<Tree<KindDO>>();
        List<KindDO> kinds = kindMapper.list(new HashMap<String, Object>(16));
        for (KindDO kind : kinds) {
            Tree<KindDO> tree = new Tree<KindDO>();
            tree.setId(kind.getKindId().toString());
            tree.setParentId(kind.getParentId().toString());
            tree.setText(kind.getName());
            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", true);
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        Tree<KindDO> t = BuildTree.build(trees);
        return t;
    }

    @Override
    public boolean checkKindHasUser(Long kindId) {
        int result = kindMapper.getKindUserNumber(kindId);
        return result == 0 ? true : false;
    }

    @Override
    public List<Long> listChildrenIds(Long parentId) {
        List<KindDO> kindDOS = list(null);
        return treeMenuList(kindDOS, parentId);
    }

    List<Long> treeMenuList(List<KindDO> menuList, long pid) {
        List<Long> childIds = new ArrayList<>();
        for (KindDO mu : menuList) {
            //遍历出父id等于参数的id，add进子节点集合
            if (mu.getParentId() == pid) {
                //递归遍历下一级
                treeMenuList(menuList, mu.getKindId());
                childIds.add(mu.getKindId());
            }
        }
        return childIds;
    }

}
